package com.nforce.linremote;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.os.Looper;
import android.widget.EditText;
import android.widget.TextView.BufferType;

public class BlockingDialog {

    private static void check() {
	if (Looper.myLooper() == Looper.getMainLooper()) {
	    throw new RuntimeException("Error: This is UI thread");
	}
    }

    public static String askArg(final Activity a, final String title, final String defaultText) throws InterruptedException {
	check();
	final Holder<String> result = new Holder<String>(defaultText);
	final Thread t = Thread.currentThread();

	a.runOnUiThread(new Runnable() {
	    @Override
	    public void run()
	    {
		final EditText input = new EditText(a);
		input.setText(result.getValue(), BufferType.NORMAL);
		AlertDialog.Builder builder = new AlertDialog.Builder(a);
		builder.setTitle(title);
		builder.setView(input);
		builder.setPositiveButton(android.R.string.ok, new OnClickListener() {

		    @Override
		    public void onClick(DialogInterface dialog, int which) {
		    }
		});

		AlertDialog dialog = builder.create();
		dialog.setOnDismissListener(new OnDismissListener()
		{

		    @Override
		    public void onDismiss(DialogInterface dialog)
		    {
			synchronized (result) {
			    result.setValue(input.getText().toString());
			    result.notify();
			}

		    }
		});
		dialog.show();

	    }
	});

	synchronized (result)
	{
	    result.wait();
	}
	return result.getValue();
    }

    public static class Holder<T>
    {
	private T value;

	public Holder(T _value)
	{
	    value = _value;
	}

	public T getValue()
	{
	    return value;
	}

	public void setValue(T value)
	{
	    this.value = value;
	}
    }
}
